import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
// Import for Android features.
import 'package:webview_flutter_android/webview_flutter_android.dart';
// Import for iOS features.
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';
class CustomWebViewWidget extends StatefulWidget {
  String _webHtml;
  CustomWebViewWidget(this._webHtml,{Key? key}) : super(key: key);

  @override
  State<CustomWebViewWidget> createState() => _WebViewWidgetState();
}

class _WebViewWidgetState extends State<CustomWebViewWidget> {

  late final WebViewController controller;
  late double progress = 0.01;  //H5加载进度值
  final double VISIBLE = 2;
  final double GONE = 0;
  late double progressHeight = GONE;

  void setProgressVisible(double visible){
    setState(() {
      progressHeight = visible;
    });
  }

  void setProgress(double progress){
    setState(() {
      this.progress = progress;
    });
  }

  @override
  void initState() {
    super.initState();
    late final PlatformWebViewControllerCreationParams params;
    if (WebViewPlatform.instance is WebKitWebViewPlatform) {
      params = WebKitWebViewControllerCreationParams(
        allowsInlineMediaPlayback: true,
        // limitsNavigationsToAppBoundDomains: true,
        mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
      );
    } else {
      params = const PlatformWebViewControllerCreationParams();
    }

    controller =
    WebViewController.fromPlatformCreationParams(params);
    controller.setJavaScriptMode(JavaScriptMode.unrestricted);
    controller.setNavigationDelegate(
          NavigationDelegate(
              onProgress: (int progress){
                // this.progress = progress.toDouble() / 100.0;  //计算成0.0-1.0之间的值
                setProgress(progress.toDouble() / 100.0);
              },
              onPageStarted: (String url){
                setProgressVisible(VISIBLE);
              },
              onPageFinished: (String url){
                setProgressVisible(GONE);
              }
          )
      );
    if(widget._webHtml.startsWith("http")) {
      controller.loadRequest(Uri.parse(widget._webHtml));
    }else{
      controller.loadHtmlString(widget._webHtml);
    }

  }

  @override
  Widget build(BuildContext context) {
    return Stack(
        children: [
          WebViewWidget(controller: controller),
          SizedBox(
            height: progressHeight,
            child: LinearProgressIndicator(
              backgroundColor: Colors.white,
              valueColor: AlwaysStoppedAnimation(Colors.blue),
              value: progress,
            ),
          )
        ]
    );
  }
}

